package cn.miju.ser.alipay.controller;

import cn.miju.alipay.model.PayResultNotifyRequest;
import cn.miju.ser.alipay.service.AlipayCallbackService;
import cn.miju.ser.framework.annotation.DirectResponse;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <pre>
 * 平台支付宝支付回调接口
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-02-27 23:09
 */
@Slf4j
@ApiIgnore
@RestController
@RequestMapping("/alipay/callback")
public class AlipayCallbackController {

    private final AlipayCallbackService service;

    public AlipayCallbackController(AlipayCallbackService service) {
        this.service = service;
    }

    /**
     * 支付结果通知
     * @return 结果 success 成功 fail：失败
     */
    @DirectResponse
    @PostMapping(value = "/pay", produces = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public String payResultNotify(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        if(requestParams.isEmpty()) {
            return "fail";
        }
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        // 验签
        //boolean signVerified = AlipaySignature.rsaCheckV2(map, AlipayConfig.alipay_public_key, AlipayConstants.CHARSET_UTF8);
        //// 验签通过
        //if (!signVerified) {
        //    return "fail";
        //}
        PayResultNotifyRequest payResultNotifyRequest = JSON.parseObject(JSON.toJSONString(map), PayResultNotifyRequest.class);
        log.info("支付结果回调通知：{}", payResultNotifyRequest.toString());
        service.payCallbackNotify(payResultNotifyRequest);
        return "success";
    }
}
